package com.lyf.controller;

import com.github.pagehelper.PageInfo;
import com.lyf.dto.ApkNameDto;
import com.lyf.dto.AppInfoDto;
import com.lyf.dto.ReviewDto;
import com.lyf.entity.AppInfo;
import com.lyf.entity.DevUser;
import com.lyf.service.AppInfoService;
import com.lyf.vo.ResultVo;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.lyf.utils.SessionUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/appInfo")
public class AppInfoController {
    @Autowired
    AppInfoService appInfoService;

    @PostMapping("/page")
    public ResultVo getPage(@RequestBody AppInfoDto appInfoDto, @RequestParam(defaultValue = "1") Integer pageNum, HttpServletRequest request){
        String token = request.getHeader("token");

        String[] split = token.split("-");
        if (split[3].equals("dev")) {
            DevUser devUser = (DevUser) SessionUtils.get(token);
            appInfoDto.setDevid(devUser.getId());
        }else{
            appInfoDto.setStatus(1L);
        }

        PageInfo<AppInfo> page = new PageInfo<>(appInfoService.getPage(appInfoDto,pageNum));
        return ResultVo.success("",page);
    }

    @PostMapping("/validate")
    public ResultVo validate(@RequestBody ApkNameDto apkNameDto){
        boolean flag = appInfoService.validate(apkNameDto);
        if(flag){
            return ResultVo.success("","");
        }else{
            return ResultVo.error("");
        }
    }

    @PostMapping("/getAppById/{id}")
    public ResultVo getAppById(@PathVariable Long id){
        AppInfo appInfo = appInfoService.getAppById(id);
        return ResultVo.success("",appInfo);
    }

    @PostMapping("/addOrUpdate")
    public ResultVo addOrUpdate(AppInfo appInfo, MultipartFile file,HttpServletRequest request){
        System.out.println(appInfo);
        if (file != null) {
            if (!file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                String extension = FilenameUtils.getExtension(originalFilename);
                if(file.getSize() < 1024*500){
                    if(
                           extension.equalsIgnoreCase("png")||
                           extension.equalsIgnoreCase("jpg")||
                           extension.equalsIgnoreCase("jpeg")||
                           extension.equalsIgnoreCase("gif")
                    ){

                        String realPath = request.getServletContext().getRealPath("/upload/logo");
                        File file1 = new File(realPath);
                        if (!file1.exists()) {
                            file1.mkdirs();
                        }
                        String str = UUID.randomUUID().toString().replace("-", "") + "." + extension;
                        try {
                            file.transferTo(new File(realPath+"/"+str));
                            appInfo.setLogopicpath("/upload/logo/"+str);
                        } catch (IOException e) {
                            e.printStackTrace();
                            return ResultVo.error("logo图片上传失败！");
                        }

                    }else{
                        return ResultVo.error("logo图片格式不正确！");
                    }
                }else{
                    return ResultVo.error("logo图片大小超过500k");
                }
            }
        }

        String token = request.getHeader("token");
        DevUser devUser = (DevUser) SessionUtils.get(token);

        if(appInfo.getId() == null){
            appInfo.setCreatedby(devUser.getId());
            appInfo.setCreationdate(new Date());
            appInfo.setStatus(1L);
            appInfo.setDownloads(0L);
            appInfo.setDevid(devUser.getId());
        }else{
            appInfo.setStatus(1L);
            appInfo.setModifyby(devUser.getId());
            appInfo.setModifydate(new Date());
        }


        try {
            System.out.println("--------");
            System.out.println(appInfo);
            appInfoService.addOrUpdate(appInfo);
            return ResultVo.success("操作成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("操作失败");
        }

    }

    @DeleteMapping("/del/{id}")
    public ResultVo del(@PathVariable Long id,HttpServletRequest request){
        try {
            appInfoService.del(id,request);
            return ResultVo.success("",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("");
        }
    }

    @PostMapping("/sale/{id}")
    public ResultVo sale(@PathVariable Long id){
        try {
            appInfoService.sale(id);
            return ResultVo.success("",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVo.error("");
        }
    }


    @PostMapping("/review")
    public ResultVo review(@RequestBody ReviewDto reviewDto){
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(reviewDto,appInfo);
        appInfoService.addOrUpdate(appInfo);
        return ResultVo.success("",null);
    }

}
